
/// App框架的底部Tabbar管理类

import 'package:flutter/material.dart';
import 'package:flutter_navigator/OSNavigator/OSNavigator.dart';
import 'package:flutter_navigator/Pages/AlarmPage.dart';
import '../Pages/HomePage.dart';
import '../Pages/MinePage.dart';

class OSTabBarNavigator extends StatefulWidget {
  @override
  _OSTabBarNavigatorState createState() => _OSTabBarNavigatorState();
}

class _OSTabBarNavigatorState extends State<OSTabBarNavigator> with AutomaticKeepAliveClientMixin {

  final _defaultColor = Colors.blue;
  final _activeColor = Colors.orange;
  int _currentIndex = 0;
  static int initialPage = 0;
  final PageController _controller = PageController(initialPage: initialPage);
  /// 缓存TabBar的所有页面
  late List<Widget> _pages;
  bool _hasBuild = false;
  @override
  Widget build(BuildContext context) {
    _pages = [
      AMHomePage(),
      AMAlarmPage(),
      AMMinePage()
    ];
    if(!_hasBuild){
      // 如果是首次初始化
      OSNavigator.getInstance().onTabBarChange(initialPage, _pages[initialPage]);
      _hasBuild = true;
    }
    return Scaffold(
      body: PageView(
        controller: _controller,
        children: _pages,
        physics: NeverScrollableScrollPhysics(),
        onPageChanged: (index) => _onJumpTo(index, pageChange: true),
      ),
      bottomNavigationBar: Theme(
        data: ThemeData(
        brightness: Brightness.light,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
        child: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: (index) => _onJumpTo(index),
          type: BottomNavigationBarType.fixed,
          selectedItemColor: _activeColor,
          unselectedItemColor: _defaultColor,
          selectedFontSize: 14,
          unselectedFontSize: 14,
          items: [
            _createBottomItem("逻辑资源",Icons.album,0),
            _createBottomItem("报警",Icons.all_out_outlined,2),
            _createBottomItem("我的",Icons.person_rounded,0),
          ],
        ),
      ),
    );
  }

  _createBottomItem(String name, IconData icon, int index) {
    return BottomNavigationBarItem(
      icon: Icon(icon,color: _defaultColor,),
      activeIcon: Icon(icon,color: _activeColor,),
      label: name,
    );
  }

  /// 点击底部TabBar Item 跳转对应页面逻辑
  void _onJumpTo(int index,{pageChange=false}) {
    if(!pageChange){
      _controller.jumpToPage(index);
    } else {
      OSNavigator.getInstance().onTabBarChange(index, _pages[index]);
    }
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
